<template>
    <div>
        <dialog-alert :data="alertData" @on-close="onCloseUploadAlert()" @on-confirm="submitForm(ruleFormRef)">
            <div class="dialog-alert"> 
                <el-form ref="ruleFormRef" :model="poetryInfo" :rules="rules" label-width="120px" class="demo-ruleForm" 
                    :size="formSize" :status-icon="false">
                    <!-- <el-form-item label="已有标签：" v-if="type == 'change'">
                        <el-col :span="20">
                            <div v-if="labelArr.length != 0">
                                <div class="label" v-for="(item, index) in labelArr" :key="item.lid">
                                    <span>{{ item.l_name }}</span>
                                    <i class="el-icon el-tag__close" @click.prevent="deleteLabel(item, index)"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M764.288 214.592 512 466.88 259.712 214.592a31.936 31.936 0 0 0-45.12 45.12L466.752 512 214.528 764.224a31.936 31.936 0 1 0 45.12 45.184L512 557.184l252.288 252.288a31.936 31.936 0 0 0 45.12-45.12L557.12 512.064l252.288-252.352a31.936 31.936 0 1 0-45.12-45.184z"></path></svg></i>
                                </div>
                            </div>
                            <div v-else><div><span style="color: var(--pc-font-black);">无</span></div></div>
                        </el-col>
                    </el-form-item>
                    <el-form-item :label="type == 'change' ? '新增标签：' : '诗歌标签'">
                        <el-col :span="20">
                            <el-cascader v-model="selectLabel" :options="typeLabelList" :show-all-levels="false" 
                                placeholder="请选择标签" :props="{multiple: true}"/>
                        </el-col>
                    </el-form-item> -->
                    <el-form-item label="诗歌名称：" prop="p_title">
                        <el-col :span="12">
                            <el-input v-model="poetryInfo.p_title"/>
                        </el-col>
                    </el-form-item>
                </el-form>
            </div>
        </dialog-alert>
    </div>
    <!-- <dialog-alert v-if="isShowAlert == 'success'" :data="sucessData" @on-confirm="onConfirm" @on-close="onCancel"></dialog-alert>
    <dialog-alert v-if="isShowAlert == 'failure'" :data="failData" @on-confirm="onConfirm" @on-close="onCancel"></dialog-alert>
    <dialog-alert v-if="isShowAlert == 'bannerImageEmpty'" :data="bannerImageEmptyData" @on-confirm="onConfirm"></dialog-alert> -->
    <dialog-alert v-if="isShowAlert == 'addSuccess'" :data="addSuccessData" @on-confirm="onConfirm" @on-close="onCancel"></dialog-alert>
    <dialog-alert v-if="isShowAlert == 'addFailure'" :data="addFailureData" @on-confirm="onConfirm"></dialog-alert>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, toRefs } from 'vue'
// import { IPoetryListModel, IPoetryModel, IDynastyModel } from '../../manage-poetry.model'
import managePoetryStore from '../../manage-poetry.store'
import manageAuthorStore from '@/page/administrator/index/page/manage-author/manage-author.store'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { IPoetryListModel } from '../../manage-poetry.model'
import { IDynastyModel } from '../../../manage-author/manage-author.model'
import { clearObject, handleElCascaderOptions, handleTypeLidID } from '@/utils/util'
import manageTypeLabelStore from "../../../manage-type-label/manage-type-label.store"

const manageTypeLabelSe = manageTypeLabelStore()
const managePoetrySe = managePoetryStore()
const manageAuthorSe = manageAuthorStore()
const props = defineProps({
    type: {
        type: String,
        default: ''
    },
    addTypeLabelData: {
        type: Object,
        default: {}
    },
    searchType: {
        type: String,
        default: ''
    },
    searchInput: {
        type: String,
        default: ''
    },
})
const { type, addTypeLabelData, searchType, searchInput } = toRefs(props)

const poetryInfo = reactive({
    pid: 0, // 诗歌id
    aid: '', // 作者id
    a_name: '', // 作者
    p_title: '', // 诗歌名称
    p_dynasty: '', // 朝代
    p_content: '', // 诗歌内容
    p_analyze: '', // 诗歌赏析
    p_translation: '', // 译文
    p_annotation: '', // 字词翻译
    p_comment: '', // 辑评
    p_genre: '诗', // 体裁
    p_cover: ''  // 封面
}) as IPoetryListModel

const genre = reactive([{id: 0 , name: '诗'}, {id: 1 , name: '词'}, {id: 2 , name: '歌'}, {id: 3 , name: '赋'}, {id: 4 , name: '文'}])

// 表单校验
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
// 校验规则
const rules = reactive<FormRules>({
    a_name: [
        { required: true, message: '请输入作者名称（如作者未知则输入‘佚名’）', trigger: ['change', 'blur'] },
    ],
    p_title: [
        { required: true, message: '请输入诗歌名称', trigger: ['change', 'blur'] },
    ],
    p_dynasty: [
        { required: true, message: '请选择朝代', trigger: ['change', 'blur'] },
    ],
    p_content: [
        { required: true, message: '请输入诗歌正文', trigger: ['change', 'blur'] },
    ],
    p_genre: [
        { required: true, message: '请输入诗歌类型', trigger: ['change', 'blur'] },
    ],
})
// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            getEditPoetry()
        } else {
            ElMessage({
                showClose: true,
                message: '提交表单失败，请检查输入是否正确！',
                type: 'error',
            })
        }
    })
}
// 清空表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    Object.assign(poetryInfo, clearObject(poetryInfo))
}

// 更新信息时给输入框赋值
const assignValueToInput = (value: IPoetryListModel) => {
    // poetryInfo = value
    poetryInfo.pid = value.pid
    poetryInfo.a_name = value.a_name
    poetryInfo.aid = value.aid
    poetryInfo.p_analyze = value.p_analyze
    poetryInfo.p_annotation = value.p_annotation
    poetryInfo.p_comment = value.p_comment
    poetryInfo.p_content = value.p_content
    poetryInfo.p_dynasty = value.p_dynasty
    poetryInfo.p_genre = value.p_genre
    poetryInfo.p_title = value.p_title
    poetryInfo.p_translation = value.p_translation
}
defineExpose({
    assignValueToInput
})

const emits = defineEmits(['onCloseEditPoetryAlert', 'getPoetryList', 'on-confirm', 'closeUploadAlert'])

// 添加成功或失败时的弹窗
let isShowAlert = ref<string>('')
// 添加成功弹窗
const addSuccessData = {
    title: '添加成功',
    message: '添加诗歌信息成功！是否继续添加？',
    confirmTitle: '确认',
    cancleTitle: '取消',
    isShowCancleBtn: true
}
// 添加失败
const addFailureData = {
    title: '添加失败',
    message: '添加诗歌信息失败！',
    confirmTitle: '确认',
}
// 点击取消
const onCancel = () => {
    Object.assign(poetryInfo, clearObject(poetryInfo))
    isShowAlert.value = ''
    emits('onCloseEditPoetryAlert', true)
    emits('getPoetryList')
}
// 点击确认
const onConfirm = () => {
    if(isShowAlert.value == 'addFailure') {
        isShowAlert.value = ''
        return
    }
    Object.assign(poetryInfo, clearObject(poetryInfo))
    isShowAlert.value = ''
}

// 添加诗歌信息
const alertData = {
    title: type.value == 'change' ? '更改诗歌信息' : '添加诗歌信息',
    confirmTitle: type.value == 'change' ? '更改' : '添加',
    isShowCancleBtn: true,
    cancleTitle: '取消',
    isShowClose: true,
    size: 'large'
}
// 弹窗内点击取消时
let isShowUploadAlert = ref<boolean>(false)
const onCloseUploadAlert = () => {
    isShowUploadAlert.value = false
    resetForm
    emits('onCloseEditPoetryAlert')
}
// 弹窗内点击确认时
const getEditPoetry = async () => {
    const { addLidString, deleteLidString } = handleTypeLidID(selectLabel.value, deleteLabelArr.value)
    if(type.value == 'change') {
        const data = {
            poetryInfo: JSON.stringify(poetryInfo),
            addLidString: addLidString,
            deleteLidString: deleteLidString
        }
        managePoetrySe.getUpadatePoetryById(data).then((res: any) => {
            if(res.status == 'success') {
                ElMessage({
                    showClose: true,
                    message: '修改成功！',
                    type: 'success',
                })
                emits('onCloseEditPoetryAlert', true)
            } else {
                ElMessage({
                    showClose: true,
                    message: '修改失败！',
                    type: 'error',
                })
            }
        })
    } else {
        poetryInfo.aid = poetryInfo.a_name
        poetryInfo.addLidString = addLidString
        console.log('poetryInfo', poetryInfo)
        managePoetrySe.getAddPoetry(poetryInfo).then((res: any) => {
            if(res.status == 'success') {
                isShowAlert.value = 'addSuccess'
            } else {
                isShowAlert.value = 'addFailure'
            }
        })
    }
}

// 根据用户输入获取作者名称
let timer = ref<any>(null)
let loading = ref<boolean>(false)
let authorList = ref([])
const SearchAuthorByName = (query: string) => {
    if(query == '') {
        authorList.value = []
        return 
    }
    loading.value = true
    if(timer.value) clearTimeout(timer.value) 
    timer.value = setTimeout(() => {
        // 发送获取作者信息请求
        const data = {
            searchType: 'A',
            searchText: query
        }
        manageAuthorSe.getSearchAuthorByDynastyOrName(data).then((res: any) => {
            loading.value = false
            if(res.status = 'success') {
                authorList.value = res.results.results2
                clearTimeout(timer.value)
            }
        })
    }, 300)
}
// 选择作者时触发
const chooseAuthor = (value: string) => {
    poetryInfo.aid = value
}

// 获取朝代
let dynastyList = ref<any>([])
const getDynasty = () => {
    manageAuthorSe.getDynasty().then((res: any) => {
        if(res.status = 'success') {
            dynastyList.value = res.results
        }
    })
}

// 获取全部标签信息
let labelArr = ref<any>([])
let selectLabel = ref<any>([])
let typeLabelList = ref<any>([])
const getTypeLabelList = () => {
    manageTypeLabelSe.getTypeLabelList().then((res: any) => {
        if(res.status == 'success') {
            addTypeLabelData.value.typeLabelListById ? labelArr.value = JSON.parse(JSON.stringify(addTypeLabelData.value.typeLabelListById.label)) : []
            typeLabelList.value = handleElCascaderOptions(res.results, addTypeLabelData.value)
        }
    })
}
onMounted(() => {
    getDynasty()
    getTypeLabelList()
})

// 删除诗歌标签
let deleteLabelArr = ref<any>([])
const deleteLabel = (item: any, index: number) => {
    deleteLabelArr.value.push(labelArr.value.slice(index, index + 1)[0].lid)
    labelArr.value.splice(index, 1)
    typeLabelList.value.forEach((item1: any) => {
        if(item1.value == item.tid) {
            item1.children.forEach((item2: any) => {
                if(item2.value == item.lid) item2.disabled = false
            })
        }
    })
}
</script>

<style lang="less" scoped>
.dialog-alert {
    height: 30rem;
    overflow: auto;
    :deep(.el-form-item.author){
        .el-input__wrapper {
            max-width: 12rem;
        }
    }
    .d-a_other-info {
        min-width: 20rem;
        max-height: 30rem;
        overflow: hidden;
        tr {
            height: 3rem;
            vertical-align: top;
            input {
                width: 25%;
            }
            .r-title {
                padding-top: 0.4rem;
            }
            .author {
                position: relative;
                .author-input {
                    border-radius: 0.3rem 0.3rem 0 0;
                }
                .author-list {
                    width: 30%;
                }
            }
            td {
                text-align-last: justify;
                input {
                    height: 2rem;
                    line-height: 2rem;
                    padding: 0 0.5rem;
                    padding-right: 1.5rem;
                    border-radius: 0.3rem;
                    border: 1px solid var(--pc-border-gray);
                    text-align-last: left;
                }
            }
            textarea {
                text-align-last: left;
            }
            :deep(.el-select) {
                .el-input__inner {
                   text-align-last: left;
               }
            }
        }
    }
}
</style>